<template>
  <b-container class="py-5">
    <b-row>
      <DetailPost 
      :previousPost="previousPost"
      :post="post"
      :nextPost="nextPost"
      />
    </b-row>
    <b-row>
      <Comment :postid="post.id"/>
    </b-row>
  </b-container>
</template>

<script>
import pubsub from "pubsub-js";
import DetailPost from "./DetailPost.vue";
import Comment from './Comment.vue'
export default {
  name: "Detail",
  components: {
    DetailPost,
    Comment,
  },
  data() {
    return {
      previousPost: {}, // 上一篇文章
      post: {}, // 当前文章
      nextPost: {} // 下一篇文章
    };
  },

  //方法
  methods: {
    getPost() {
      const read_post_id = window.sessionStorage.getItem("read_post_id");
      let reqParams = {
        params: { read_post_id: read_post_id },
      };
      this.$http.get("/blog/detail/" + this.$route.params.id, reqParams).then(
        (res) => {
          const { meta, data } = res.data;
          // Ajax发送成功，但是未查询到正确数据
          if (meta.code != 200) return console.log(meta.msg);
          // 查询到正确数据
          const { previousPost, post, nextPost } = data;
          this.previousPost = previousPost;
          this.post = post;
          this.nextPost = nextPost;
          window.sessionStorage.setItem("read_post_id", post.id);
          pubsub.publish("showPostTitle", this.post);
        },
        (error) => {
          // Ajax 请求失败
          console.log(error);
        }
      );
    },
  },

  //监视属性
  watch:{
    // 监视路由变化，更新数据
    $route() {
      this.getPost();
    },
  },

  // 生命周期函数
  mounted(){
    this.getPost();
  },

    // 销毁前生命周期钩子
  beforeDestroy() {
    pubsub.publish("showPostTitle", {});
  },
};
</script>

<style>
</style>